<?php

namespace yunxmall\oauth;

use common\helpers\StringHelper;
use linslin\yii2\curl\Curl;

/**
 * QQ OAuth
 * @author xjflyttp <xjflyttp@gmail.com>
 */
class YXAuth
{
    const MODEL_DOMAIN = 1;//授权域名模式
    const MODEL_AUTOGRAPH = 2;//签名模式

    public $model;//

    public $authUrl = 'http://yc.51moki.com/authorization.php';

    public function __construct($m = self::MODEL_DOMAIN)
    {
        $this->model = $m;
    }

    /**
     * @throws \Exception
     */
    public function init()
    {
        if ($this->model == self::MODEL_DOMAIN) {
            $domain = $_SERVER['SERVER_NAME'];
            $cacheKey = StringHelper::cacheKey('__SERVER_AUTH' . $domain);
            if (!\Yii::$app->cache->exists($cacheKey)) {
                $curl = new Curl();
                $auth = $curl->setPostParams([
                    'url' => $domain
                ])->post($this->authUrl);
                if ($auth == 1) {
                    \Yii::$app->cache->set($cacheKey, $auth, 24 * 60 * 60);
                }
            } else {
                $auth = \Yii::$app->cache->get($cacheKey);
            }

            if ($auth != 1) {
                die('未授权的域名，请联系管理员！'.$domain);
                exit;
            }
        }
    }

    /**
     * 处理加密参数
     */
    public function initRequest(){
        if(\Yii::$app->request->isPost && !$_FILES){
            $amc = \Yii::$app->request->post('amc',null);

            if(!is_null($amc)){
                $key = '@yunxiankeji4512';

                \Yii::$app->request->setBodyParams([]);
                $_data = openssl_decrypt($amc, 'AES-128-CBC', $key, OPENSSL_ZERO_PADDING, 'ZZWBKJ_ZHIHUAWEI');
                if(!empty($_data)){
                    $_data = rtrim($_data, "\0");
                    $_d = json_decode($_data, true);
                    \Yii::$app->request->setBodyParams($_d);
                }
            } else {
                throw new UnprocessableEntityHttpException('参数有误');
            }
        }
    }

    protected function initUserAttributes()
    {
    }


}
